//
//  MyNavigator.swift
//  Game
//
//  Created by woniu on 2025/8/26.
//

import Foundation
import UIKit

class MyNavigator {
    
    /// push一个控制器
    /// - Parameter vc: 待显示的VC
    class func push(_ vc:UIViewController) {
        self.showVC(vc)
    }
    
    ///返回到指定页面，返回跳转成功、失败
    class func popTo(vcClass:AnyClass,animated:Bool = true)->Bool{
        if let topNav = self.topNaVC(){
            for subVC in topNav.children{
                if subVC.self.isKind(of: vcClass){
                    topNav.popToViewController(subVC, animated: animated)
                    return true
                }
            }
        }
        return false
    }
    
    
    ///返回到指定页面
    @discardableResult
    class func popTo(vc:UIViewController,animated:Bool = true)->Bool{
        let nav = topNaVC()
        let list = nav?.children ?? []
        for subVC in list.reversed(){
            if subVC == vc{
                nav?.popToViewController(subVC, animated: animated)
                return true
            }
        }
        return false
    }
    
    ///返回上一个页面
    class func findLastVC()->UIViewController?{
        guard let topNav = self.topNaVC() else{return nil}
        let subChildren = topNav.children
        if subChildren.count <= 1{
            return nil
        }
        return subChildren[subChildren.count-2]
    }
    
    /// 显示一个控制器，若有导航控制器则push，否则present
    /// - Parameter vc: 需要显示的VC
    private class func showVC(_ vc:UIViewController){
        if let navigation = MyNavigator.topNaVC(){
            
            navigation.pushViewController(vc, animated: true)
        }else{
            let navigationVC = UINavigationController(rootViewController: vc)
            navigationVC.navigationBar.isHidden = true
            let window = MyNavigator.getWindow()
            window?.rootViewController?.present(navigationVC, animated:true, completion: nil)
        }
    }
    
    
    //打开app权限设置页面
    static func openSetingPage() {
        let url = URL(string:UIApplication.openSettingsURLString)
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!, options: [:], completionHandler: {
                (bool)in
            })
        }
    }
    //打开系统设置
    static func openSystemSetingPage() {
        //防止审核被拒，因为这个私有方法，通过字符串拼接看是否可以骗过机审
        var urlStr = "App"
        urlStr.append("-")
        urlStr.append("pref")
        urlStr.append("s:roo")
        urlStr.append("t=Gene")
        urlStr.append("ral")
        let url = URL(string: UIApplication.OpenURLOptionsKey.init(rawValue:urlStr).rawValue)
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!, options: [:], completionHandler: {
                (bool)in
            })
        }
    }
}

extension MyNavigator{
    
    // 获取当前活动的navigationcontroller
    class func topNaVC() -> UINavigationController? {
        
        guard let window = getWindow() else{return nil}
        if let tabBarVC = window.rootViewController as? UITabBarController{
            if let vc = tabBarVC.selectedViewController as? UINavigationController{
                return vc
            }
        }
        if let navVC = window.rootViewController as? UINavigationController{
            return navVC
        }
        
        return nil
    }
    
    ///获取活动窗口
    class func getWindow()->UIWindow?{
        
        if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene{
            for window in scene.windows{
                if window.isKeyWindow{
                    return window
                }
            }
        }
        return nil
    }
    
    /// 当前显示控制器是否是指定类型
    /// - Parameter vcs: 入参页面类型列表
    /// - Returns: 是否正在显示
    class func isShowing(vcs:[AnyClass])->Bool{
        if let old =  MyNavigator.getTopVC(){
            for vc in vcs{
                if old.isKind(of: vc) || old.isMember(of: vc){
                    return true
                }
            }
        }
        return false
    }
    
    
    /// 获取顶层控制器 根据window
    /// - Returns: 正在显示的VC
    class func getTopVC() ->UIViewController?{
        let vc = getWindow()?.rootViewController
        return getTopVC(withCurrentVC: vc)
    }
    
    
    ///根据控制器获取 顶层控制器
    class func getTopVC(withCurrentVC:UIViewController?) -> UIViewController? {
        if withCurrentVC == nil {
            return nil
        }
        if let presentVC = withCurrentVC?.presentedViewController {
            return getTopVC(withCurrentVC: presentVC)
            
        }else if let tabVC = withCurrentVC as? UITabBarController {
            if let selectVC = tabVC.selectedViewController {
                return getTopVC(withCurrentVC: selectVC)
            }
            return nil
            
        } else if let naiVC = withCurrentVC as? UINavigationController {
            return getTopVC(withCurrentVC:naiVC.visibleViewController)
            
        } else {
            return withCurrentVC
        }
    }
}
